<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/4
 * Time: 11:51
 */

namespace app\common\model\teacher;


use app\admin\model\PageResponse;
use app\common\model\app\ConstLinkType;
use app\common\model\dynamic\DynamicFlowItem;
use app\common\model\dynamic\DynamicFlowItemColumn;
use app\common\model\dynamic\DynamicFlowItemTeacher;
use app\common\model\DynamicFlow;
use app\common\model\IMakeDynamicFlow;
use app\common\model\SpecialColumn;
use app\common\model\UserNoticeMessage;
use app\common\utils\DateTimeUtil;
use app\common\utils\ObjectUtil;
use app\common\utils\OssUtil;
use library\JPushZDY;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;

/**
 * Class TeacherEssay
 * @package app\common\model\teacher
 *
 * @property integer id
 * @property integer teacher_id
 * @property string title
 * @property string summary
 * @property string cover
 * @property string content
 * @property string tags
 * @property string created
 * @property integer catalog_id
 * @property integer num_liked
 * @property integer click_rate
 * @property boolean recommend
 * @property boolean hide
 * @property boolean free
 * @property string ref_source
 * @property string|array attachment
 * @property string special_column_id
 * @property object bind_course
 */
class TeacherEssay extends Model implements IMakeDynamicFlow
{
    protected $table = 'teacher_essay';
    protected $pk = 'id';
    protected $field = [
        'id',
        'title',
        'cover',
        'teacher_id',
        'content',
        'summary',
        'tags',
        'hide',
        'catalog_id',
        'recommend',
        'ref_source',
        'special_column_id',
        'attachment',
        'stocks',
        'bind_course',
        'num_liked',
    ];

    private static $SaveFields = [
        'title',
        'cover',
        'teacher_id',
        'content',
        'created',
        'summary',
        'tags',
        'hide',
        'num_liked',
        'catalog_id',
        'recommend',
        'ref_source',
        'special_column_id',
        'attachment',
        'stocks',
        'bind_course',
    ];
    public static function getSaveFields(): array {
        return self::$SaveFields;
    }

    public function encodeJSON() {
        if (isset($this->ref_source) && (is_array($this->ref_source) || is_object($this->ref_source)))
            $this->ref_source = json_encode($this->ref_source,JSON_UNESCAPED_UNICODE);

        if (isset($this->attachment) && (is_array($this->attachment) || is_object($this->attachment)))
            $this->attachment = json_encode($this->attachment,JSON_UNESCAPED_UNICODE);
    }
    public function decodeJSON() {
        if (isset($this->ref_source) && is_string($this->ref_source))
            $this->ref_source = json_decode($this->ref_source,true);

        if (isset($this->attachment) && is_string($this->attachment))
            $this->attachment = json_decode($this->attachment,true);
    }

    public function save($data = [], $where = [], $sequence = null)
    {
        if (is_string($this->tags)) {
            $this->tags = explode(',',$this->tags);
        }

        if (is_array($this->tags)) {
            $this->tags = implode(',',array_values(array_filter($this->tags)));
        }

        return parent::save($data, $where, $sequence);
    }

    public static function init()
    {
        static::event('before_write', function (TeacherEssay $model) {
            $model->encodeJSON();
        });

        static::event('after_write', function (TeacherEssay $model) {
            $model->decodeJSON();
        });

        static::event('after_insert', function (TeacherEssay $model) {
            if ($model->teacher_id) Teacher::countNumEssay($model->teacher_id);
        });

    }

    public static function getDynamicClass($special_column_id) {
        if ($special_column_id > 0) return DynamicFlow::CLASS_COLUMN;
        else return DynamicFlow::CLASS_ESSAY;
    }

    /**
     * 管理端 列表
     * @param int $limit
     * @param int $offset
     * @param int $catalog_id
     * @param int $teacher_id
     * @param string $keywords
     * @param int $special_column_id
     * @return PageResponse
     */
    public static function manageList(int $limit, int $offset, $catalog_id = 0, $teacher_id = -1,
                                      $keywords = null, $special_column_id = -1) {

        $filter = $keywords ? " AND e.title like :kw " : null;
        $params = ['limit' => $limit, 'offset' => $offset,];

        if ($keywords) $params['kw'] = "%$keywords%";
        if ($catalog_id > 0) {
            $ids=TeacherEssayCatalog::findByParentId($catalog_id,'id',true);
            if($ids){
                $catalog_id=implode(',',$ids);
                $filter .= ' AND e.catalog_id in ('.$catalog_id.')';
            }else{
                $filter .= ' AND e.catalog_id=:catalog_id';
                $params['catalog_id'] = $catalog_id;
            }
        }
        if ($teacher_id != -1) {
            $filter .= ' AND e.teacher_id=:teacher_id';
            $params['teacher_id'] = $teacher_id;
        }
        if ($special_column_id != -1) {
            $filter .= ' AND e.special_column_id=:special_column_id ';
            $params['special_column_id'] = $special_column_id;
        }

        $sql = <<<SQL
SELECT e.*,c.name catalog_name,sc.column_title
FROM teacher_essay e
LEFT JOIN teacher_essay_catalog c ON c.id=e.catalog_id
LEFT JOIN special_column sc ON sc.column_id=e.special_column_id
WHERE TRUE {$filter}
ORDER BY e.id DESC 
LIMIT :limit OFFSET :offset
SQL;
        $list = Db::query($sql, $params);

        $sql = <<<SQL
SELECT count(e.id) as num FROM teacher_essay e
WHERE TRUE {$filter}
SQL;
        unset($params['limit'], $params['offset']);
        $re = Db::query($sql, $params);
        $total = $re[0]['num'] ?? 0;
        if($list){
            foreach ($list as &$v){
                $v['stocks'] = json_decode($v['stocks'],true);
                $v['bind_course'] = json_decode($v['bind_course'],true);
                // $list[$k]['stocks']=json_decode($v['stocks'],true);
            }
        }
        return PageResponse::success($list, $total);
    }

    public static function del($id, $teacher_id = 0) {
        $sql = 'delete from teacher_essay where id=:id ';
        $params = ['id' => $id];
        if ($teacher_id > 0) {
            $sql .= ' and teacher_id=:teacher_id';
            $params['teacher_id'] = $teacher_id;
        }
        $sql .= ' RETURNING id,teacher_id,special_column_id';
        $re = Db::query($sql, $params);
        if (empty($re)) return;
        $re = $re[0];

        if ($re['teacher_id'] > 0) Teacher::countNumEssay($re['teacher_id']);

        $class = self::getDynamicClass($re['special_column_id']);
        DynamicFlow::del($class, $re['id']);
    }

    public static function setHide($id, $hide, $teacherId = 0) {

        Db::transaction(function () use ($id,$hide,$teacherId) {
            $sql = 'update teacher_essay set hide=:hide where id=:id ';
            $params = ['id'=>$id,'hide'=>$hide?1:0];
            if ($teacherId > 0) {
                $sql .= ' AND teacher_id=:tid ';
                $params['tid'] = $teacherId;
            }
            $sql .= ' RETURNING * ';
            $re = Db::query($sql, $params);
            if (empty($re)) return;

            /**
             * @var static $model
             */
            $model = ObjectUtil::assign(static::class, $re[0]);

            if ($model->teacher_id > 0) Teacher::countNumEssay($model->teacher_id);

            if ($hide) {
                $class = self::getDynamicClass($model->special_column_id);
                DynamicFlow::del($class, $model->id);
            } else {
                if ($model->teacher_id > 0) {
                    $model->makeDynamicData(false, $teacherId>0 ? DynamicFlow::SOURCE_TEACHER : DynamicFlow::SOURCE_ADMIN);
                }
            }
        });

    }

    public static $DefaultCover = OssUtil::DNS_HOST.'/static/img/essay_default_cover.png';

    /**
     * API 列表
     *
     * @param int $limit
     * @param int $offset
     * @param int $teacher_id
     * @param null $type
     * @param int $catalog_id
     * @param bool $recommend
     * @param bool $pageTotal
     * @param int $uid
     * @param int $special_column_id
     * @return array|null
     */
    public static function apiList(int $limit, int $offset, int $teacher_id = 0, $type = null, int $catalog_id = 0,
                                   $recommend = false, $pageTotal = false, $uid = 0, $special_column_id = null) {

        $params = ['limit'=>$limit, 'offset'=>$offset];
        $where = '';
        $fields = '';

        if (null !== $special_column_id) {
            $where .= ' AND e.special_column_id=:special_column_id ';
            $params['special_column_id'] = $special_column_id;
        }
        //modify cc 在老师详情页面去除内参和研报的文章
        if($teacher_id>0){
            $interId = config('course_serivce.internalReferenceId');
            $researchRId = config('course_serivce.researchReportId');
            if($interId>0 && $researchRId>0){
                $where .= ' AND e.catalog_id !='.$interId.' AND e.catalog_id != '.$researchRId.' ';
            }
        }

        if (1 == $type) {
            if ($teacher_id > 0) {
                $where .= ' AND e.teacher_id>0 AND e.teacher_id=:teacher_id ';
                $params['teacher_id'] = $teacher_id;
            } else {
                $where .= ' AND e.teacher_id > 0 ';
            }
        } elseif (2 == $type) {
            $where .= ' AND e.teacher_id = 0 ';
        } else {
            if ($teacher_id > 0) {
                $where .= ' AND e.teacher_id>0 AND e.teacher_id=:teacher_id ';
                $params['teacher_id'] = $teacher_id;
            }
        }

        if ($catalog_id > 0) {
            $where .= ' AND e.catalog_id=:catalog_id ';
            $params['catalog_id'] = $catalog_id;
        }
        if ($recommend) {
            $where .= ' AND e.recommend=true ';
        }
        if ($uid > 0) {
            $fields .= ', exists(SELECT 1 FROM user_follow_teacher uft WHERE uft.userid=:uid and uft.teacher_id=e.teacher_id limit 1) followd';
            $params['uid'] = $uid;
        }

        $sql = <<<SQL
SELECT e.id,e.title,e.teacher_id,e.cover,e.summary,e.created,e.recommend,e.tags,e.catalog_id,e.special_column_id,
  e.ref_source->>'name' source_name,ref_source->>'url' source_url,ref_source->>'logo' source_logo,
  t.realname AS teacher_name,t.avatar,
  c.name catalog_name,sc.column_title special_column_title
  {$fields}
FROM teacher_essay e LEFT JOIN teacher t ON e.teacher_id=t.id 
LEFT JOIN teacher_essay_catalog c ON e.catalog_id=c.id
LEFT JOIN special_column sc ON e.special_column_id=sc.column_id
WHERE e.hide=FALSE {$where} 
ORDER BY id DESC 
LIMIT :limit OFFSET :offset 
SQL;
        $list = Db::query($sql, $params);

        self::formatList($list);

        if ($pageTotal) {
            $sql = <<<SQL
SELECT count(*) total
FROM teacher_essay e LEFT JOIN teacher t ON e.teacher_id = t.id
WHERE e.hide=FALSE {$where}
SQL;
            unset($params['limit'],$params['offset'],$params['uid']);
            $re = Db::query($sql, $params);
            $total = $re[0]['total'] ?? null;

            return ['list' => $list, 'total' => $total];
        } else {
            return $list;
        }
    }

    /**
     * 获取最新
     *
     * @param int $num
     * @return mixed
     */
    public static function listTop(int $num) {
        $sql = <<<SQL
SELECT e.id,e.title,e.teacher_id,e.cover,e.summary,e.created,e.attachment, t.realname teacher_name,t.avatar,
   e.ref_source->>'name' source_name,ref_source->>'url' source_url,ref_source->>'logo' source_logo
FROM teacher_essay e
LEFT JOIN teacher t ON e.teacher_id = t.id
WHERE e.hide=FALSE AND e.special_column_id=0
ORDER BY e.id DESC 
LIMIT :num
SQL;
        $list = Db::query($sql, ['num' => $num]);

        self::formatList($list);

        return $list;
    }

    /**
     * API 详情
     *
     * @param int $id
     * @param bool $loadByUrl
     * @param int $uid
     * @return array|null
     */
    public static function apiDetail(int $id, int $uid, bool $loadByUrl = false) {

        $join = '';
        $params = ['id' => $id];
        $fields = '';
        if ($uid > 0) {
            $fields .= <<<TEXT
,exists(SELECT 1 FROM user_essay_collection c WHERE c.essay_id=e.id AND c.userid=:uid) AS collected
,exists(SELECT 1 FROM user_essay_liked c WHERE c.essay_id=e.id AND c.userid=:uid) AS liked
,exists(SELECT 1 FROM user_subscribe_special c WHERE c.ust_special=e.special_column_id AND c.ust_user=:uid AND c.ust_is_effective AND c.ust_expiry_date>:currtime) subscribed
TEXT;
            $params['uid'] = $uid;
            $params['currtime'] = time();
        }

        if ($loadByUrl) {
            $sql = <<<SQL
SELECT e.id,e.title,e.cover,e.summary,e.created,e.num_liked,e.teacher_id,e.special_column_id, t.realname AS teacher_name,t.avatar,
  e.ref_source->>'name' source_name,ref_source->>'url' source_url,ref_source->>'logo' source_logo
{$fields} 
FROM teacher_essay e
LEFT JOIN teacher t ON e.teacher_id = t.id
{$join}
WHERE e.id=:id
SQL;
        } else {
            $sql = <<<SQL
SELECT e.*,t.realname AS teacher_name,t.avatar,
  e.ref_source->>'name' source_name,ref_source->>'url' source_url,ref_source->>'logo' source_logo
{$fields}
FROM teacher_essay e 
LEFT JOIN teacher t ON e.teacher_id = t.id
{$join}
WHERE e.id=:id
SQL;
        }
        $result = Db::query($sql, $params);
        if (empty($result) || count($result)==0) return null;
        $result = $result[0];

        self::format($result);

        if ($uid <= 0) {
            $result['collected'] = $result['liked'] = false;
        }

        $result['share_url'] = self::shareUrl($result['id']);

        return $result;
    }

    /**
     * @deprecated
     * 格式日期时间
     *
     * @param $time
     * @param $fmt
     * @return string
     */
    private static function time_format($time, $fmt) {
        $created = strtotime($time);
        $dt = $_SERVER['REQUEST_TIME'] - $created;
        if ($dt < 3600) {
            $time = floor($dt / 60).'分钟前';
        } elseif ($dt >= 3600 && $dt < 18000) {
            $time = floor($dt / 3600).'小时前';
        } else {
            $time = date($fmt, $created);
        }
        return $time;
    }

    public static function gave_like(int $uid, int $essay_id, bool $gave = true) {

        if ($gave) {
            $sql = <<<SQL
INSERT INTO user_essay_liked (userid, essay_id) VALUES (:uid, :eid)
ON CONFLICT DO NOTHING 
SQL;
        } else {
            $sql = <<<SQL
DELETE FROM user_essay_liked WHERE userid=:uid AND essay_id=:eid
SQL;
        }

        try{
            Db::startTrans();
            $n = Db::execute($sql, ['uid'=>$uid, 'eid'=>$essay_id]);

            if ($n > 0) {
                $inc = $gave ? 1 : -1;
                $sql = <<<SQL
UPDATE teacher_essay SET num_liked=num_liked+:inc WHERE id=:id
SQL;
                Db::execute($sql, ['id'=>$essay_id,'inc'=>$inc]);
            }

            Db::commit();

            return true;
        }catch (Exception $ex){
            Db::rollback();
            return false;
        }

    }

    /**
     * 用户添加收藏
     * @param int $uid
     * @param int $essay_id
     * @param bool $add
     * @return bool
     */
    public static function collect(int $uid, int $essay_id, bool $add = true) {

        if ($add) {
            $sql = <<<SQL
INSERT INTO user_essay_collection (userid, essay_id) VALUES (:uid, :eid)
ON CONFLICT DO NOTHING 
SQL;
        } else {
            $sql = <<<SQL
DELETE FROM user_essay_collection WHERE userid=:uid AND essay_id=:eid
SQL;
        }
        try{
            $n = Db::execute($sql, ['uid'=>$uid, 'eid'=>$essay_id]);

            return true;
        }catch (Exception $ex){
            return false;
        }
    }

    /**
     * 获取用户的图文收藏列表
     *
     * @param int $uid
     * @param int $rows
     * @param int $page
     * @param bool $pageTotal
     * @return mixed
     */
    public static function collectionList(int $uid, int $rows = 10, int $page = 1, $pageTotal = false) {

        $query =
        Db::table('user_essay_collection c')
            ->join('teacher_essay e', 'e.id=c.essay_id')
            ->join('teacher t','t.id=e.teacher_id','LEFT')
            ->where('c.userid','=',$uid)
            ->where('e.hide=false')
            ->order('c.created','DESC')
            ->field('
            e.id,
            e.title,
            e.cover,
            e.summary,
            e.tags,
            e.teacher_id,
            t.realname as teacher_name,
            e.created,
            e.ref_source->>\'name\' source_name,
            ref_source->>\'url\' source_url,
            ref_source->>\'logo\' source_logo
            ')
        ;
        if ($pageTotal) {
            $result = $query->paginate($rows,false, ['page'=>$page]);
            $list = $result->items();
            self::formatList($list);
            $total = $result->total();
            return ['list' => $list, 'total' => $total];
        } else {
            $list = $query->page($page, $rows)->select();
            self::formatList($list);
            return $list;
        }

    }

    /**
     * 累计点击量
     *
     * @param $id
     */
    public static function click($id) {
        $sql = <<<SQL
UPDATE teacher_essay SET click_rate = click_rate + 1 WHERE id=:id
SQL;
        Db::execute($sql, ['id' => $id]);
    }

    /**
     * 热门咨询列表
     *
     * @param int $num
     * @return mixed
     */
    public static function hotList($num = 8) {
        $sql = <<<SQL
SELECT e.id,e.title,e.created, t.realname teacher_name 
FROM teacher_essay e
LEFT JOIN teacher t ON e.teacher_id = t.id
ORDER BY click_rate DESC, id DESC 
LIMIT :num
SQL;
        $list = Db::query($sql, ['num' => $num]);
        foreach ($list as & $item) {
            $item['created'] = DateTimeUtil::format($item['created']);
        }

        return $list;
    }

    public static function getByTeacher($teacherId, $num, $column_id = 0) {
        $sql = <<<SQL
SELECT id,title,created 
FROM teacher_essay WHERE teacher_id=:teacher_id AND special_column_id=:column_id
ORDER BY id DESC
LIMIT :num
SQL;
        $list = Db::query($sql, ['teacher_id'=>$teacherId, 'num' => $num, 'column_id' => $column_id]);
        foreach ($list as & $item) {
            $item['created'] = DateTimeUtil::format($item['created']);
        }

        return $list;
    }

    private static function formatList(& $list) {
        foreach ($list as & $item) {
            self::format($item);
        }
    }

    private static function format(& $item) {

        if (isset($item['tags']) && is_string($item['tags'])) $item['tags'] = array_values(array_filter(explode(',',$item['tags'])));

        // if (isset($item['created'])) $item['created'] = DateTimeUtil::format($item['created']);
        if (isset($item['created'])) $item['created'] = tranTime(strtotime($item['created']));

        if (isset($item['teacher_id']) && 0 == $item['teacher_id']) {
            $item['teacher_name'] = $item['source_name'];
            $item['avatar'] = $item['source_logo'];
        }

        if (isset($item['attachment']) && is_string($item['attachment'])) {
            $item['attachment'] = json_decode($item['attachment']);
            $item['attachment']->has_video = isset($item['attachment']->video);
            $item['attachment']->has_audio = isset($item['attachment']->audio);
        }
        if (empty($item['attachment'])) {
            $item['attachment'] = new \stdClass();
        }

        if (empty($item['cover']) ) $item['cover'] = self::$DefaultCover;

        if (isset($item['special_column_id'])) $item['in_column'] = $item['special_column_id'] > 0;

        $item['share_url'] = self::shareUrl($item['id']);

    }

    public static function shareUrl($id) {
        return config('server.host') . '/site/share/essay_detail/id/'.$id;
    }

    /**
     * 产生老师动态并保存到数据库
     *
     * @param bool $isNew
     * @param integer $source
     * @return DynamicFlow
     * @throws Exception
     */
    public function makeDynamicData(bool $isNew, int $source = DynamicFlow::SOURCE_SYSTEM): DynamicFlow
    {
        if ($this->teacher_id <= 0) {
            throw new Exception('只有老师发布资讯才能产生动态', 1);
        }
        $teacher = Teacher::get($this->teacher_id);
        if (is_null($teacher)) {
            throw new Exception('数据错误，不正确的老师id', 2);
        }

        $dynamic = new DynamicFlow();
        $dynamic->df_time = time();
        $dynamic->df_source = $source;
        $dynamic->df_isfee = false;
        $dynamic->df_isnew = $isNew;

        $item = new DynamicFlowItem();
        $item->item_id = (int) $this->id;
        $item->item_title = $this->title;
        if (isset($this->cover)) $item->item_cover = $this->cover;
        $item->item_summary = $this->summary;

        $item_teacher = new DynamicFlowItemTeacher();
        $item_teacher->teacher_id = (int) $teacher->id;
        $item_teacher->teacher_name = $teacher->realname;
        $item_teacher->teacher_avatar = $teacher->avatar ?? Teacher::DEFAULT_AVATAR;
        $item_teacher->teacher_degree = $teacher->getDegreeName();
        $item->item_teacher = $item_teacher;

        if (isset($this->special_column_id)) {
            $column = SpecialColumn::get($this->special_column_id);
            if ($column) {
                $item_column = new DynamicFlowItemColumn();
                $item_column->column_id = $column->column_id;
                $item_column->column_name = $column->column_title;
                $item->item_column = $item_column;
                $dynamic->df_isfee = $column->column_price>0 ? false : true;
                $dynamic->df_class = DynamicFlow::CLASS_COLUMN;
            }
        }
        if (!isset($dynamic->df_class)) $dynamic->df_class = DynamicFlow::CLASS_ESSAY;

        // 动态类型
        $this->decodeJSON();
        if (isset($this->attachment['audio'])) {
            $dynamic->df_type = DynamicFlow::TYPE_AUDIO;
            $item->item_duration = $this->attachment['audio']['duration'] ?? 0;
        }
        elseif (isset($this->attachment['video'])) {
            $dynamic->df_type = DynamicFlow::TYPE_VIDEO;
            $item->item_duration = $this->attachment['video']['duration'] ?? 0;
        }
        else $dynamic->df_type = DynamicFlow::TYPE_RICH_TEXT;

        $dynamic->df_value = $item;
        $dynamic->save();

        return $dynamic;
    }


    public static function getPagination(array $condition=[],$rows=10,$filed='*',$order='created desc'){
        return self::where($condition)->field($filed)->order($order)->paginate($rows)->toArray();
    }

    public static function getOriginalPagination(array $condition=[],$rows=10,$filed='*',$order='created desc'){
        return self::alias('te')->where($condition)->join('teacher t','te.teacher_id=t.id')->field($filed)->order($order)->paginate($rows)->toArray();
    }

    public static function getLimit(array $condition=[],$limit=10,$filed='*',$order='created desc',$branch=0,$changeFormat=true){
        $data=self::where($condition)->field($filed)->order($order)->limit($limit)->select();
        if($changeFormat){
            return self::changeFormat($data,$branch);
        }else{
            return $data;
        }
    }

    public static function getById($id,$field='*'){
        return self::where('id',$id)->field($field)->find();
    }

    public static function getList(array $condition=[],$rows=10,$filed='*',$order='e.created desc'){
        return self::alias('e')
            ->join('teacher t', 'e.teacher_id=t.id', 'left')
            ->where($condition)->field($filed)->order($order)->limit($rows)->select();
    }


    /**
     * 转换资讯数据格式
     * @param array $data
     * @param int $branch
     * @return array
     */
    public static function changeFormat(array $data=[],$branch=0){
        foreach ($data as $k=>$v){
            $data[$k]['cover']=$v['cover']??TeacherEssay::$DefaultCover;
            $data[$k]['title']=isset($v['title']) ? htmlspecialchars_decode($v['title']) : '';
            $data[$k]['summary']=isset($v['title']) ? htmlspecialchars_decode($v['summary']) : '';
            $data[$k]['created']=isset($v['created']) ? date('Y-m-d H:i:s',strtotime($v['created'])) : '';
            if($branch==1) $data[$k]['is_special']=(isset($v['special_column_id']) && $v['special_column_id']>0) ? true : false;
        }
        return $data;
    }

    public static function getPointPagination(array $condition=[],$rows=10,$filed='*',$order='created desc'){
         //modify cc 2018-10-17 去除观点的专栏文章
         $where2=['te.hide' => 'false','te.teacher_id'=>['<>',0],'te.special_column_id'=>['=',0]];
         return self::alias('te')->join('teacher t','te.teacher_id=t.id','left')->where(function ($q) use($condition){
             $q->where($condition);
         })->whereOr(function ($q) use($where2){
             $q->where($where2);
         })->field($filed)->order($order)->paginate($rows)->toArray();
    }

    /**
     * getTypeNewsList
     * 根据分类获取资讯列表
     *
     * @param int $pid 文章分类父类id
     * @param int $limit 获取文章条数
     * @return TeacherEssay[]|false
     * @throws \think\exception\DbException
     */
    public static function getTypeNewsList($pid, $limit=3)
    {
        $data = self::all(function ($query) use ($pid, $limit) {
            $query->alias('news');
            $query->join('teacher_essay_catalog type', 'news.catalog_id=type.id', 'left');
            $query->where('type.parent_id', $pid);
            $query->where('news.hide', 'false');
            //modify cc 2018-10-16 去掉专栏文章
            $query->where('news.special_column_id', 0);
            $query->field('news.id, news.title, news.cover, news.created, news.summary, news.ref_source->>\'name\' as source_name');
            $query->order('news.created desc');
            $query->limit($limit);
        });

        foreach ($data as &$val) {
            $val['created'] = tranTime(strtotime($val['created']));
            $val['source_name'] = $val['source_name']?:'掌乾财经';
            $val['cover']=$val['cover'] ? $val['cover'] : TeacherEssay::$DefaultCover;
        }

        return $data;
    }


    public static function getPaginationByBindcourse($page,$rows=10,$course_id,$catalog_id,$filed='*'){
        $page=intval($page);
        $offset=($page-1)*$rows;
        $sql="SELECT ".$filed." FROM teacher_essay WHERE  hide = false and catalog_id= ".$catalog_id." and bind_course @> '[".$course_id."]' order by created desc LIMIT ".$rows." OFFSET ".$offset;
        $data=self::query($sql);
        $sql="SELECT count(1) FROM teacher_essay WHERE  hide = false and catalog_id= ".$catalog_id." and bind_course @> '[".$course_id."]'";
        $total=self::query($sql)[0]['count']??0;
        return $result=[
            'total'=>$total,
            'per_page'=>$rows,
            'current_page'=>$page,
            'last_page'=>ceil($total/$rows),
            'data'=>$data
        ];
    }

    /**
     * articleUpdatePushMsg
     * 文章更新消息推送
     *
     * @param $articleId
     * @param int $type
     * @return bool
     *
     * todo 系统消息、普通文章
     */
    public static function articleUpdatePushMsg($articleId, $type=1)
    {
        $article = Db::query("select * from teacher_essay where hide=false and id=:id", ['id'=>$articleId]);

        if (!$article) return false;

        $article = $article[0];

        $articleTitle = $article['title'];
        $catalogId = $article['catalog_id'];
        $bindCourse = $article['bind_course'];
        $bindCourse = json_decode($bindCourse, true);
        $bindCourse = $bindCourse?implode(',', $bindCourse):0;

        $internalReferenceId = config('course_serivce.internalReferenceId');
        $researchReportId = config('course_serivce.researchReportId');

        switch ($type) {
            case 1: // 课程服务文章
                if (($catalogId==$internalReferenceId) || ($catalogId==$researchReportId)){

                    if ($catalogId==$internalReferenceId) $service = '内参';
                    if ($catalogId==$researchReportId) $service = '研报';


                    // 使用文章绑定的课程查询出购买了这些课程的用户
                    $buyCourse = Db::query("select uc_user from user_buy_curriculum where uc_curriculum in (:courseId)", ['courseId'=>$bindCourse]);
                    $user = array_column($buyCourse, 'uc_user');
                    $msg = "掌乾财经：{$service}最新消息《{$articleTitle}》。";
                    $extras = UserNoticeMessage::makeExtras(ConstLinkType::LINK_TYPE_ESSAY, $article['id']);
                    $res = JPushZDY::pushUsers($user, $msg, $extras);
                }
                break;
            case 2: // 普通文章
                break;
        }

        /*Log::info("文章更新消息推送：");
        Log::info($res);*/
    }
}
